<template>
  <div class="container">
    <div class="left-panel">
      <div style="font-size:25px; margin-bottom:10px" slot="header">
        发布文章
      </div>
      <el-card class="text-card">
        <el-form :model="formData" ref="formData" label-width="80px">
          <el-form-item label="标题" prop="title">
            <el-input v-model="formData.title" placeholder="请输入文章标题"></el-input>
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <el-input type="textarea" v-model="formData.content" placeholder="请输入文档内容"></el-input>
          </el-form-item>
          <el-form-item label="类别" prop="category">
            <el-input v-model="formData.category" placeholder="请输入文章类别"></el-input>
          </el-form-item>
          <el-form-item label="作者" prop="author">
            <el-input v-model="formData.author" placeholder="请输入文章作者"></el-input>
          </el-form-item>
          
          <el-button type="info" @click="openUploadDialog">一键上传文章</el-button>
          <el-button type="primary" @click="publishText" style="margin-left: 220px;">发布</el-button>
        </el-form>
      </el-card>
      <el-dialog title="文章内容" :visible.sync="isText" :modal="false">
        <div class="text-content">
          <p>{{ textContent }}</p>
        </div>
      </el-dialog>
      <el-dialog title="一键上传文章" :visible.sync="uploadDialogVisible" :modal="false">
        <p>请下载样例 Word 文件,按规定格式上传文章。</p>
        <el-button type="primary" @click="downloadSample">下载样例文件</el-button>
        
        <el-upload
          class="upload-demo"
          drag
          :action="`${baseUrl}/admin/autoAddText`"
          :show-file-list="true"
          :before-upload="beforeUpload"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">拖拽文件到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-dialog>
    </div>
    
    <div class="right-panel">
      <div style="font-size:25px; margin-bottom:10px; display: flex; justify-content: space-between; align-items: center;">
        <span>已发布文章</span>
        <el-input
          placeholder="搜索文章"
          v-model="searchQuery"
          style="width: 200px; margin-left:50px;"
          suffix-icon="el-icon-search"
          @input="filterArticles"
        ></el-input>
      </div>
      <el-card class="text-list-card" style="overflow: auto; max-width: 100%;">
        <el-table :data="filteredTextList" style="width: 100%">
          <el-table-column prop="title" label="标题" align="center"></el-table-column>
          <el-table-column prop="created_at" label="创建时间" align="center"></el-table-column>
          <el-table-column prop="updated_at" label="更新时间" align="center"></el-table-column>
          <el-table-column label="操作" align="center">
            <template v-slot="scope">
              <el-button type="info" @click="viewArticle(scope.row)">查看全文</el-button>
              <el-button type="danger" @click="deleteArticle(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import baseUrl from '../assets/path.js';

export default {
  data() {
    return {
      formData: {
        title: '',
        content: '',
        category: '',
        author: ''
      },
      textList: [],
      filteredTextList: [],
      searchQuery: '',
      baseUrl,
      uploadDialogVisible: false,
      isText: false,
      textContent: ''
    };
  },
  
  mounted() {
    this.fetchArticles();
  },
  
  methods: {
    fetchArticles() {
      axios.get(`${this.baseUrl}/admin/getText`)
        .then(response => {
          this.textList = response.data.map(article => ({
            ...article,
            created_at: this.formatDate(article.created_at), // 格式化创建时间
            updated_at: this.formatDate(article.updated_at)  // 格式化更新时间
          }));
          this.filteredTextList = this.textList; // 初始化过滤列表
          this.filterArticles(); // 根据当前搜索查询过滤文章
        })
        .catch(error => {
          console.error("获取文章列表失败:", error);
          this.$message.error("获取文章列表失败");
        });
    },
  
    publishText() {
      const { title, content, category, author } = this.formData;
      if (!title || !content || !category || !author) {
        this.$message.error('发布文章失败，所有字段均不能为空。');
        return;
      }
      
      axios.post(`${this.baseUrl}/admin/addArticles`, this.formData)
        .then(response => {
          this.fetchArticles(); // 发布文章成功后重新获取文章列表
          this.$message.success('文章发布成功！');
          this.formData = { title: '', content: '', category: '', author: '' };  // 清空表单
        })
        .catch(error => {
          this.$message.error('发布文章失败，请重试。');
        });
    },
  
    deleteArticle(article) {
      this.$confirm('您确定要删除这篇文章吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`${this.baseUrl}/admin/deleteText/${article.id}`)
          .then(response => {
            this.textList = this.textList.filter(item => item.id !== article.id);
            this.filteredTextList = this.filteredTextList.filter(item => item.id !== article.id);
            this.$message.success('文章删除成功');
          })
          .catch(error => {
            console.error("删除文章失败:", error);
            this.$message.error("删除文章失败");
          });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
  
    viewArticle(article) {
      this.textContent = article.content;
      this.isText = true;
    },
  
    beforeUpload(file) {
      const isDocx = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
      const isDoc = file.type === 'application/msword';
      const isPdf = file.type === 'application/pdf';
      
      if (!isDocx && !isDoc && !isPdf) {
        this.$message.error('上传文件只能是 Word 或 PDF 格式!');
      }
      return isDocx || isDoc || isPdf;
    },
  
    openUploadDialog() {
      this.uploadDialogVisible = true;
    },
  
    downloadSample() {
      const sampleFileUrl = `${this.baseUrl}/static/example/text.docx`;
      window.open(sampleFileUrl);
    },
  
    handleUploadSuccess(response, file) {
      this.$message.success(`${file.name} 文件上传成功！`);
      this.fetchArticles();
    },
  
    handleUploadError(err, file) {
      this.$message.error(`${file.name} 文件上传失败！`);
    },
  
    filterArticles() {
      const query = this.searchQuery.toLowerCase(); // 将搜索查询转为小写以便比较
      this.filteredTextList = this.textList.filter(article => {
        return (
          article.title.toLowerCase().includes(query) || // 根据标题过滤
          article.content.toLowerCase().includes(query) // 根据内容过滤
        );
      });
    },
  
    formatDate(dateString) {
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份并补零
      const day = String(date.getDate()).padStart(2, '0'); // 获取日期并补零
      const hours = String(date.getHours()).padStart(2, '0'); // 获取小时并补零
      const minutes = String(date.getMinutes()).padStart(2, '0'); // 获取分钟并补零
  
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    }
  }

};
</script>

<style>
.container {
  display: flex;
  justify-content: space-between; 
  margin-top: 100px;
  padding: 20px;
}
.text-card {
  width: 330px;
}
.left-panel {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.right-panel {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.el-card {
  height: 400px;
}
.text-list-card {
  width: 1000px;
  height: 400px; 
  overflow: auto;
}
.instruction {
  font-size: 12px;
  color: #888;
  margin-top: 5px;
}
.el-table th, .el-table td {
  text-align: center;
}
.upload-demo {
  margin: 20px 0;
}
.text-content {
  text-align: justify; /* 两端对齐 */
  text-indent: 2em; /* 首行缩进两格 */
}
.text-content p {
  margin: 0; /* 去除段落上下的默认间距 */
}
.el-dialog {
  height: 500px;
}
</style>
